package com.zhanglu.gateway.security;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * @description token工具类
 * @Auther zhanglu
 * @Date 2017/10/13 下午4:56
 */
public class JwtUtil {
    public static String secret = "fun-auth-info"; // key暂时不加密，由字符串代替
    public static final String COOKIE_AUTH = "user_token";// cookie名字，值是token，统一

    public static String createJWT(AuthenticationUser user, List<String> roles) {
        return Jwts.builder()
                .setSubject(user.getUsername())
                .setIssuer("Fun_ZL")
                .claim("expireDate", user.getExpireDate())
                .claim("email", user.getEmail())
                .claim("password", user.getPassword())
                .claim("gender", user.getGender())
                .claim("age", user.getAge())
                .claim("idCard", user.getIdCard())
                .claim("roles", roles.stream().collect(Collectors.joining(",")))
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
    }

    public static AuthenticationUser parserToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList(claims.get("roles", String.class));
        return new AuthenticationUser(
                claims.getSubject(),
                claims.get("password", String.class),
                claims.get("email", String.class),
                claims.get("gender", Boolean.class),
                claims.get("age", Integer.class),
                claims.get("idCard", String.class),
                claims.get("expireDate", Date.class),
                token,
                auths
        );
    }
}
